package com.huaqing.save;

import com.huaqing.pojo.Result;
import lombok.Data;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @program: javatrainingfirstweek
 * @Description: 双检锁/双重校验锁
 * @author: Mr.Cheng
 * @date: 2022/4/10 4:02 下午
 */
@Data
public class SingletonMemory {
    private List<Result> resultList = null;
    private static  boolean qwe = false;

    private volatile static SingletonMemory singleton;

    private SingletonMemory(){
        if (qwe==false){
            qwe = true;
        }else {
            throw new RuntimeException("这是单例对象!");
        }
        this.resultList = new CopyOnWriteArrayList<>();
    }

    public static SingletonMemory getSingleton(){
        if(singleton == null){
            synchronized (SingletonMemory.class){
                if(singleton == null){
                    singleton = new SingletonMemory();
                }
            }
        }
        return singleton;
    }

    public void saveResults(String[] res) {
        Result result = new Result();
        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < res.length; i++) {
            if (res[i].equals("平局")){
                continue;
            }
            if (map.containsKey(res[i])) {
                int temp = map.get(res[i]);
                map.put(res[i], temp + 1);
            } else {
                map.put(res[i], 1);
            }
        }
        Collection<Integer> count = map.values();
        String maxName = null;
        if (count.size()!=0){
            int maxCount = Collections.max(count);
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                if (maxCount == entry.getValue()) {
                    maxName = entry.getKey();
                }

            }
            result.setWinnerName(maxName);
        }
        for (int i = 0; i < res.length; i++) {
            if (res[i].equals(maxName)){
                result.setWin(result.getWin()+1);
            }else if (res[i].equals("平局")){
                result.setEven(result.getEven()+1);
            }else {
                result.setDefeat(result.getDefeat()+1);
            }
        }
        resultList.add(result);
    }

}
